<template>
    <div style="width: 95%;margin: auto;">
        <el-form :inline="true" :model="userForm" class="demo-form-inline">
            <el-form-item style="width: 180px;">
                <el-input v-model="userForm.username" placeholder="请输入业主名称" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-select v-model="userForm.rid" placeholder="请选择类型" clearable style="width: 200px;">
                    <el-option label="管理员" value="102" />
                    <el-option label="普通用户" value="100" />
                    <el-option label="vip用户" value="101" />
                </el-select>
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-input v-model="userForm.phone" placeholder="电话" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-select v-model="userForm.isdelete" placeholder="是否可用" clearable>
                    <el-option label="不可用" value="1" />
                    <el-option label="可用" value="0" />
                </el-select>
            </el-form-item>

            <el-form-item style="width: 180px;">
                <el-button type="primary" @click="findAll(1)">查询</el-button>
                <el-button @click="resetForm()">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 新增和修改对话框 -->
    <div style="width: 95%;margin: auto;">
        <el-button type="primary" @click="showDialog()" :icon="Plus"> 新增</el-button>
        <el-button type="primary" @click="batchedDeleteByIds()" :icon="Delete"> 批量删除</el-button>
    </div>
    <div>
        <!-- 新增用户和修改对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="25%" draggable :show-close="false"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <!-- 新增用户表单 -->
            <el-form :inline="true" :model="dialog.user" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="dialog.user.username" placeholder="请输入用户名" clearable
                        style="width: 200px;height: 35px;" />
                </el-form-item>
                <!-- 显示上传图片 -->
                <div
                    style="position:  absolute;top: 50px;left: 240px; width: 30%; height: 100px;background-color:#FAFAFA ;text-align: center;border-radius: 5px;">
                    <el-image @click="showUploadImageDialog()" :src="dialog.user.imgpath"
                        style="border-radius: 5%;width: 100%;" />
                    <!-- <el-button @click="showUploadImageDialog()"
                        style="width: 90px;height: 10px;background-color: #FAFAFA;line-height: 10px;font-size: 12px;">添加图片</el-button> -->
                </div>

                <!-- <el-select v-model="dialog.user.rid" placeholder="选择用户类型" clearable style="width: 200px;">
                    
                    <el-option label="管理员" :value="102" />
                    <el-option label="vip用户" :value="101" />
                    <el-option label="普通用户" :value="100" />
                </el-select> -->
                <el-input v-model="dialog.user.email" :rows="2" placeholder="输入邮箱"
                    style="width: 340px;margin-top: 20px;" />
                <el-input v-model="dialog.user.phone" :rows="2" placeholder="输入电话"
                    style="width: 340px;margin-top: 20px;" />
                <el-form-item style="margin-top: 20px;">
                    <el-button type="primary" @click="insertAndUpdateUser">{{ dialog.btnText }}</el-button>
                    <el-button type="primary" @click="clearFormData">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>

    <div>
        <!-- 新增用户和修改对话框 -->
        <el-dialog v-model="uploadDialog.visible" title="文件上传" width="30%" draggable>
            <el-upload :action="uploadDialog.uploadUrl" list-type="picture-card" :file-list="fileList"
                :limit="uploadDialog.limit" :auto-upload="uploadDialog.autoUpload" :on-change="handlerImage">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <!-- 添加上传按钮 -->
            <el-form-item style="margin-top: 10px;margin-left: 320px;">
                <el-button type="primary" @click="uploadHandler()">上传</el-button>
            </el-form-item>
        </el-dialog>
    </div>

    <!-- 所有用户信息展示 -->
    <el-table :data="userPage.users" style="width: 95% ; margin:auto" @selection-change="handleSelectionChange">
        <!-- 添加复选框选项 -->
        <el-table-column type="selection" width="55" />
        <el-table-column fixed prop="uid" label="编号" width="80" />
        <el-table-column prop="username" label="姓名" width="120" />
        <el-table-column label="角色信息" width="120">
            <template #default="scope">
                <div v-for="(role, index) in scope.row.roles">
                    <el-tag v-if="role.rname == '普通用户'" type="primary">{{ role.rname }}</el-tag>
                    <el-tag v-else-if="role.rname == '管理员'" type="danger">{{ role.rname }}</el-tag>
                    <el-tag v-else-if="role.rname == 'vip用户'" type="success">{{ role.rname }}</el-tag>
                    <el-tag v-else type="info">{{ role.rname }}</el-tag>
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="300" />
        <el-table-column prop="phone" label="电话" width="200" />
        <el-table-column label="头像" prop="imgpath" width="150px">
            <!-- 插槽 -->
            <template #default="scope">
                <!-- <el-image style="width: 80px;border-radius: 5%;":src="scope.row.imgPath"/> -->
                <el-avatar shape="circle" :size="50" :src="scope.row.imgpath" />
            </template>
        </el-table-column>
        <el-table-column prop="isdelete" label="是否可用" min-width="80">
            <!-- 插槽 -->
            <template #default="scope">
                <!-- 当 scope.row.isdelete 的值等于 0 时，会渲染一个类型为 primary（主要，通常是蓝色）的标签 -->
                <el-tag v-if="scope.row.isdelete == 0" type="primary">可用</el-tag>
                <!-- 渲染一个类型为 danger（危险，通常是红色）的标签 -->
                <el-tag v-else type="danger">不可用</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" min-width="160" fixed="right">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
                    修改
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                <div>
                    <el-button link v-if="scope.row.isdelete != 0" type="warning" size="small"
                        @click="AllocateRoles(scope.row)" disabled>分配角色</el-button>
                    <el-button link v-if="scope.row.isdelete == 0" type="warning" size="small"
                        @click="AllocateRoles(scope.row)">分配角色</el-button>
                </div>

            </template>
        </el-table-column>
    </el-table>

    <!-- 分配角色对话框 -->
    <div>
        <el-dialog v-model="rolesDialog.visible" :title="rolesDialog.title" width="40%" draggable>
            <!-- 单选按钮组：只能选择一个角色 -->
            <el-radio-group v-model="rolesDialog.selectedRoleId"
                style="display: flex; gap: 20px; flex-wrap: wrap; padding: 10px 0;">
                <!-- 循环所有角色，每个角色对应一个单选按钮 -->
                <el-radio v-for="role in rolesDialog.allRoles" :key="role.rid" :label="role.rid" border
                    style="padding: 8px 16px;">
                    {{ role.rname }} <!-- 显示角色名称 -->
                </el-radio>
            </el-radio-group>

            <!-- 提交按钮（居中） -->
            <div style="text-align: center; margin-top: 24px;">
                <el-button type="primary" @click="UpdateRoles()">分配</el-button>
            </div>
        </el-dialog>
    </div>

    <!-- 分页标签 -->
    <div style="width: 95%;margin: 10px auto;">
        <el-pagination background layout="prev, pager, next" v-model:page-size="userForm.pageSize"
            v-model:current-page="userForm.pageNum" :total="userForm.total" @current-change="findAll" />
    </div>
</template>
<script lang="ts" setup>

import { ref, reactive, onMounted } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'


const userPage = reactive({
    users: [],//存放后端查询用户数据变量
})

//声明一个对象用于条件查询
let userForm = ref({
    pageNum: 0,
    pageSize: 8,
    total: 0,
})
//根据条件查询信息
const findAll = async (currentpage) => {
    userForm.value.pageNum = currentpage;
    let res = await request.post("/user/queryCondition", userForm.value);
    if (res.data.success) {

        userPage.users = res.data.data.list;
        console.log(userPage.users);


        userForm.value.pageNum = res.data.data.pageNum;
        userForm.value.pageSize = res.data.data.pageSize;
        userForm.value.total = res.data.data.total;
    }

}
const resetForm = (() => {
    userForm.value.username = "";
    userForm.value.rid = null;
    userForm.value.phone = "";
    userForm.value.isdelete = null;
})
onMounted(() => {
    findAll(1);
});
//定义对话框属性
const dialog = ref({
    visible: false,
    title: '',
    btnText: '',
    user: {},
})
//定义变量控制文件上传
const uploadDialog = reactive({
    visible: false, //隐藏对话框
    uploadUrl: "",
    fileList: [], //保存所有上传文件集合
    limit: 1,//控制文件上传个数
    autoUpload: false,
    uploadFile: null as File | null,
})

//实现用户新增或者修改操作
const insertAndUpdateUser = async () => {
    if (dialog.value.btnText == "新增") {
        //查看是否有值
        //发送请求实现熊增用户功能
        let res = await request.post("/user/insert", dialog.value.user);
        //判断是否新增成功
        if (res.data.success) {
            //1.清空表单
            clearFormObj();
            //2.刷新页面
            findAll(1);
            //3.显示提示信息
            ElMessage.success("添加成功")
            //4.关闭对话框
            dialog.value.visible = false;
        }
    } else {//表示修改
        //1.获取数据发送请求实现修改用户信息
        let res = await request.put("/user/update", dialog.value.user);

        //判断是否新增成功
        if (res.data.success) {
            //1.清空表单
            clearFormObj();
            //2.刷新页面
            findAll(userForm.value.pageNum);//查询当前页
            //3.显示提示信息
            ElMessage.success("修改成功")
            //4.关闭对话框
            dialog.value.visible = false;
        }
    }
}

//显示文件上传对话框
const showUploadImageDialog = () => {
    uploadDialog.visible = true;
}

//显示修改用户对话框
const handleEdit = (index, row) => {
    //显示表单信息
    dialog.value.user = row;
    //设置对话框标题
    dialog.value.title = "修改用户";
    //设置按钮文本内容
    dialog.value.btnText = "更新数据";
    //显示对话框
    dialog.value.visible = true;
}

//显示新增对话框
const showDialog = () => {
    //1.设置对话框标题
    dialog.value.title = "新增用户";
    //2.设置对话框 案例文本
    dialog.value.btnText = "新增";
    //3.清空表单
    clearFormObj();
    //4.显示对话框
    dialog.value.visible = true;
}

//选中文件时触发函数
const handlerImage = (file) => {
    uploadDialog.uploadFile = file.raw;
}
const clearFormData = () => {
    dialog.value.visible = false; // 关闭对话框
    findAll(userForm.value.pageNum);
}
//清空表单函数
const clearFormObj = () => {
    dialog.value.user.username = '';
    dialog.value.user.rid = 100;
    dialog.value.user.email = '';
    dialog.value.user.imgpath = 'https://org-yixue-ykj-bucket.oss-cn-nanjing.aliyuncs.com/avatar/cxy.jpg';
    dialog.value.user.phone = '';
    dialog.value.user.uid = '';
}
//实现文件上传函数
const uploadHandler = async () => {

    //文件上传详细步骤
    //1.创建FormData对象
    let formData = new FormData();
    //2.设置上传对象对象
    formData.append("file", uploadDialog.uploadFile)
    //3.设置上传类型
    let contentType = { "ContentType": "multipart/form-data" }
    formData.append("headers", contentType);
    //4.发送请求实现文件上传
    let res = await request.post("/user/fileUpload", formData);
    if (res.data.success) {
        //把上传文件保存到表单imgPath中
        dialog.value.user.imgpath = res.data.data; //http://localhost:80/xxxx.png
        //显示提示信息
        ElMessage.success("上传成功");
        //关闭文件上传对话框
        uploadDialog.visible = false;
    }
}

// 角色分配所需属性以及方法（单选版 - 修复后）
let rolesDialog = reactive({
    visible: false,          // 对话框显示状态
    title: "分配角色信息",    // 对话框标题
    userId: 0,               // 当前操作的用户ID（关键：用于后端关联）
    selectedRoleId: null,    // 选中的「单个角色ID」（单选核心）
    allRoles: [],            // 所有角色列表（格式：{rid: 100, rname: '普通用户'}）
});

// 打开分配角色对话框（初始化角色列表和默认选中值）
const AllocateRoles = async (row: any) => {
    // 1. 重置对话框状态
    rolesDialog.visible = false;
    rolesDialog.selectedRoleId = null;
    rolesDialog.userId = row.uid;  // 存储当前用户ID

    try {
        // 2. 加载所有角色列表（调用后端角色查询接口）
        const res = await request.get("/roles/findAll");
        if (!res.data.success) throw new Error("获取角色列表失败");
        rolesDialog.allRoles = res.data.data;  // 保存角色列表

        // 3. 初始化默认选中值（用户已有角色的第一个ID，无角色则为空）
        if (row.roles && row.roles.length > 0) {
            rolesDialog.selectedRoleId = row.roles[0].rid;  // 单选：取第一个角色ID
        }

        // 4. 显示对话框
        rolesDialog.visible = true;
    } catch (err) {
        ElMessage.error((err as Error).message || "打开角色分配失败");
    }
};

// 提交角色分配（调用后端更新接口）
const UpdateRoles = async () => {
    // 1. 校验：必须选择一个角色
    if (rolesDialog.selectedRoleId === null || rolesDialog.selectedRoleId === undefined) {
        ElMessage.warning("请选择一个角色");
        return;
    }

    try {
        // 2. 构造请求参数（后端需接收「用户ID + 单个角色ID」）
        const params = {
            userId: rolesDialog.userId,        // 用户ID
            roleId: rolesDialog.selectedRoleId // 选中的单个角色ID（关键：替换原数组）
        };

        // 3. 调用后端接口（注意：确认接口路径和参数名与后端一致！）
        // 若后端要求路径传参（如 /user/updateRole/{userId}/{roleId}），需调整为：
        // const res = await request.put(`/user/updateRole/${rolesDialog.userId}/${rolesDialog.selectedRoleId}`);

        const res = await request.put(`/user/updateUserRoleById/${rolesDialog.userId}/${rolesDialog.selectedRoleId}`);  // 示例：请求体传参

        // 4. 处理响应
        if (res.data.success) {
            ElMessage.success("角色分配成功");
            findAll(userForm.value.pageNum);  // 刷新当前页数据
            rolesDialog.visible = false;      // 关闭对话框
        } else {
            throw new Error(res.data.message || "角色分配失败");
        }
    } catch (err) {
        ElMessage.error((err as Error).message || "角色分配请求失败");
    }
};

//删除行操作
const handleDelete = async (row) => {
    console.log(row);
    // 假设 row 中包含 id 字段，构造包含 id 的请求体
    let requestData = { id: row.id };
    let res = await request.put(`/user/deleteById/${row.uid}`);
    if (res.data.success) {
        ElMessage.success("删除成功");
        findAll(1); // 重新获取数据，更新列表
    } else {
        ElMessage.error("删除失败");
    }
};
// 批量删除
//定义数组，存放批量删除元素集合
const users = reactive({
    usersIds: [],
})
//复选框被选择触发函数
const handleSelectionChange = (rows) => {
    users.usersIds = rows;
}
const batchedDeleteByIds = async () => {
    //1.判断数组中是否包含删除元素
    if (users.usersIds.length <= 0) {
        ElMessage.warning("请选择删除项...")
        return; //结束
    }
    let ids = [];
    //2.遍历数组，获取所有id值
    for (let i = 0; i < users.usersIds.length; i++) {
        let u = users.usersIds[i];

        //把值添加到数组中
        ids.push(u.uid);
    }
    const idsStr = ids.toString();
    //3.发送异步请求
    let response = await request.delete(`/user/deleteByIds/${ids}`, { params: { idsStr } });
    if (response.data.success) {
        //显示提示信息
        ElMessage.success("批量删除成功")
        //刷新页面
        findAll(1);
    } else ElMessage.error("批量删除失败");
}
</script>